import os
import re
import json

# 指定要搜索的目录
search_dir = '/home/user/OH/openHarmonyMaster/test/xts/acts'  # 替换为你的实际目录路径
output_file = 'partname-hapname.json'  # 输出的JSON文件路径

# 定义正则表达式模式来匹配part_name和hap_name
part_name_pattern = re.compile(r'part_name\s*=\s*"([^"]*)"')
hap_name_pattern = re.compile(r'hap_name\s*=\s*"([^"]*)"')

# 初始化一个列表来存储结果
results = []

# 遍历目录及其子目录中的所有文件
for root, dirs, files in os.walk(search_dir):
    for file in files:
        if file == 'BUILD.gn':
            file_path = os.path.join(root, file)
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()

                # 使用正则表达式查找所有part_name和hap_name
                part_names = part_name_pattern.findall(content)
                hap_names = hap_name_pattern.findall(content)

                # 假设part_names和hap_names的长度相同，且按顺序对应
                for part_name, hap_name in zip(part_names, hap_names):
                    # 将结果添加到列表中
                    results.append({
                        'part_name': part_name,
                        'hap_name': hap_name
                    })

# 将结果写入JSON文件
with open(output_file, 'w', encoding='utf-8') as f:
    json.dump(results, f, ensure_ascii=False, indent=4)

print(f'匹配结果已写入 {output_file}')